﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Admin_AjaxController : AreasController
    {
        public IManagerService _manager { get; set; }
        public IUsersService _user { get; set; }
        public INavigationService _navigation { get; set; }
        public IManager_roleService _manager_role { get; set; }
        public IOrdersService _orders { get; set; }
        public IManager_logService _manager_log { get; set; }
        public ISms_templateService _sms_template { get; set; }
        public IMail_templateService _mail_template { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        public IUser_amount_logService _user_amount_log { get; set; }
        public IUser_oauthService _user_oauth { get; set; }
        public IUser_oauth_appService _user_oauth_app { get; set; }
        public ISite_paymentService _site_payment { get; set; }
        public IWebHostEnvironment _env { get; set; }
        private Userconfig userConfig;
        private Orderconfig orderConfig;
        private Sysconfig sysConfig;
        private AliSMS sendSMS;
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            //检查管理员是否登录
            if (!IsAdminLogin())
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"尚未登录或已超时，请登录后操作！\"}");
                return;
            }
            userConfig = Common.XMLConfig.Userconfig.loadConfig(_env.ContentRootPath);
            orderConfig = Common.XMLConfig.Orderconfig.loadConfig(_env.ContentRootPath);
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            sendSMS = new AliSMS(sysConfig.smsusername, sysConfig.smspassword, sysConfig.smssignname);
            //取得处事类型
            string action = Request.Query["action"];
            switch (action)
            {
                case "username_validate": //验证用户名
                    username_validate(context);
                    break;
                case "navigation_validate": //验证导航菜单别名是否重复
                    navigation_validate(context);
                    break;
                case "manager_validate": //验证管理员用户名是否重复
                    manager_validate(context);
                    break;
                case "get_navigation_list": //获取后台导航字符串
                    get_navigation_list(context);
                    break;
                case "get_remote_fileinfo": //获取远程文件的信息
                    get_remote_fileinfo(context);
                    break;
                case "sms_message_post": //发送手机短信
                    sms_message_post(context);
                    break;
                case "edit_order_status": //修改订单信息和状态
                    edit_order_status(context);
                    break;
                case "send_red_pack": //发送红包
                    send_red_pack(context);
                    break;
                case "send_cash": //发送工资
                    send_cash(context);
                    break;
            }
        }
        public IActionResult Index()
        {
            return Content("AdminAPI");
        }
        #region ManagerLogin
        private bool IsAdminLogin()
        {
            //如果Session为Null
            if (HttpContext.Session.Get(CMSKeys.SESSION_ADMIN_INFO) != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = HttpContext.Request.Cookies["AdminName"];
                string adminpwd = HttpContext.Request.Cookies["AdminPwd"];
                if (!string.IsNullOrEmpty(adminname) && !string.IsNullOrEmpty(adminpwd))
                {
                    var model = _manager.GetModel(adminname, adminpwd);
                    if (model != null)
                    {
                        HttpContext.Session.Set(CMSKeys.SESSION_ADMIN_INFO, ByteConvertHelper.Object2Bytes(model));
                        return true;
                    }
                }
            }
            return false;
        }
        private Manager GetAdminInfo()
        {
            if (IsAdminLogin())
            {
                var model = ByteConvertHelper.Bytes2Object<Manager>(HttpContext.Session.Get(CMSKeys.SESSION_ADMIN_INFO));
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        } 
        #endregion
        #region 验证用户名是否可用OK============================
        private void username_validate(ActionExecutingContext context)
        {
            string username = Request.Form["param"];
            //如果为Null，退出
            if (string.IsNullOrEmpty(username))
            {
                context.Result=Content("{ \"info\":\"用户名不可为空\", \"status\":\"n\" }");
                return;
            }
            //过滤注册用户名字符
            string[] strArray = userConfig.regkeywords.Split(',');
            foreach (string s in strArray)
            {
                if (s.ToLower() == username.ToLower())
                {
                    context.Result=Content("{ \"info\":\"该用户名不可用\", \"status\":\"n\" }");
                    return;
                }
            }
            //查询数据库
            if (!_user.Exists(username.Trim()))
            {
                context.Result = Content("{ \"info\":\"该用户名可用\", \"status\":\"y\" }");
                return;
            }
            context.Result = Content("{ \"info\":\"该用户名已被注册\", \"status\":\"n\" }");
            return;
        }
        #endregion
        #region 验证导航菜单别名是否重复========================
        private void navigation_validate(ActionExecutingContext context)
        {
            string navname = CMSRequest.GetString("param",context.HttpContext);
            string old_name = CMSRequest.GetString("old_name",context.HttpContext);
            if (string.IsNullOrEmpty(navname))
            {
                context.Result=Content("{ \"info\":\"该导航别名不可为空！\", \"status\":\"n\" }");
                return;
            }
            if (navname.ToLower() == old_name.ToLower())
            {
                context.Result = Content("{ \"info\":\"该导航别名可使用\", \"status\":\"y\" }");
                return;
            }
            //检查保留的名称开头
            if (navname.ToLower().StartsWith("channel_"))
            {
                context.Result = Content("{ \"info\":\"该导航别名系统保留，请更换！\", \"status\":\"n\" }");
                return;
            }
            if (_navigation.Exists(navname))
            {
                context.Result = Content("{ \"info\":\"该导航别名已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Result = Content("{ \"info\":\"该导航别名可使用\", \"status\":\"y\" }");
            return;
        }
        #endregion
        #region 验证管理员用户名是否重复========================
        private void manager_validate(ActionExecutingContext context)
        {
            string user_name = Request.Form["param"];
            if (string.IsNullOrEmpty(user_name))
            {
                context.Result=Content("{ \"info\":\"请输入用户名\", \"status\":\"n\" }");
                return;
            }
            if (_manager.Exists(user_name))
            {
                context.Result = Content("{ \"info\":\"用户名已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Result = Content("{ \"info\":\"用户名可使用\", \"status\":\"y\" }");
            return;
        }
        #endregion
        #region 获取后台导航字符串==============================
        private void get_navigation_list(ActionExecutingContext context)
        {
            Manager adminModel = GetAdminInfo();//获得当前登录管理员信息
            if (adminModel == null)
            {
                return;
            }
            Manager_role roleModel = _manager_role.GetModel(adminModel.role_id);//获得管理角色信息
            if (roleModel == null)
            {
                return;
            }
            var dt = _navigation.GetList(0, CMSEnums.NavigationEnum.System.ToString());
            StringBuilder sb = new StringBuilder();
            this.get_navigation_childs(context, dt, 0, roleModel.role_type, roleModel.manager_role_values,sb);
            context.Result = Content(sb.ToString());
            return;
        }
        private void get_navigation_childs(ActionExecutingContext context, List<Navigation> oldData, int parent_id, int role_type, List<Manager_role_value> ls,StringBuilder sb)
        {
            var dr = oldData.Where(a => a.parent_id == parent_id).ToList();
            bool isWrite = false;//是否输出开始标签
            for (int i = 0; i < dr.Count; i++)
            {
                //检查是否显示在界面上====================
                bool isActionPass = true;
                if (dr[i].is_lock== 1)
                {
                    isActionPass = false;
                }
                //检查管理员权限==========================
                if (isActionPass && role_type > 1)
                {
                    string[] actionTypeArr = dr[i].action_type.Split(',');
                    foreach (string action_type_str in actionTypeArr)
                    {
                        //如果存在显示权限资源，则检查是否拥有该权限
                        if (action_type_str == "Show")
                        {
                            Manager_role_value modelt = ls.Find(p => p.nav_name == dr[i].name && p.action_type == "Show");
                            if (modelt == null)
                            {
                                isActionPass = false;
                            }
                        }
                    }
                }
                //如果没有该权限则不显示
                if (!isActionPass)
                {
                    if (isWrite && i == (dr.Count - 1) && parent_id > 0)
                    {
                        sb.AppendLine("</ul>\n");
                    }
                    continue;
                }
                //如果是顶级导航
                if (parent_id == 0)
                {
                    sb.AppendLine("<div class=\"list-group\">\n");
                    sb.AppendLine("<h1 title=\"" + dr[i].sub_title + "\">");
                    if (!string.IsNullOrWhiteSpace(dr[i].icon_url))
                    {
                        if (dr[i].icon_url.StartsWith("."))
                        {
                            sb.AppendLine("<i class=\"iconfont " + dr[i].icon_url.Trim('.') + "\"></i>");
                        }
                        else
                        {
                            sb.AppendLine("<img src=\"" + dr[i].icon_url + "\" />");
                        }
                    }
                    sb.AppendLine("</h1>\n");
                    sb.AppendLine("<div class=\"list-wrap\">\n");
                    sb.AppendLine("<h2>" + dr[i].title + "<i class=\"iconfont icon-arrow-down\"></i></h2>\n");
                    //调用自身迭代
                    this.get_navigation_childs(context, oldData, dr[i].id, role_type, ls, sb);
                    sb.AppendLine("</div>\n");
                    sb.AppendLine("</div>\n");
                }
                else//下级导航
                {
                    if (!isWrite)
                    {
                        isWrite = true;
                        sb.AppendLine("<ul>\n");
                    }
                    sb.AppendLine("<li>\n");
                    sb.AppendLine("<a navid=\"" + dr[i].name + "\"");
                    if (!string.IsNullOrEmpty(dr[i].link_url))
                    {                        
                        dr[i].link_url = "/Admin/"+ dr[i].link_url;
                        if (dr[i].channel_id > 0)
                        {
                            sb.AppendLine(" href=\"" + dr[i].link_url + "?channel_id=" + dr[i].channel_id + "\" target=\"mainframe\"");
                        }
                        else
                        {
                            sb.AppendLine(" href=\"" + dr[i].link_url + "\" target=\"mainframe\"");
                        }
                    }
                    if (!string.IsNullOrEmpty(dr[i].icon_url))
                    {
                        sb.AppendLine(" icon=\"" + dr[i].icon_url + "\"");
                    }
                    sb.AppendLine(" target=\"mainframe\">\n");
                    sb.AppendLine("<span>" + dr[i].title + "</span>\n");
                    sb.AppendLine("</a>\n");
                    //调用自身迭代
                    this.get_navigation_childs(context, oldData, dr[i].id, role_type, ls,sb);
                    sb.AppendLine("</li>\n");

                    if (i == (dr.Count - 1))
                    {
                        sb.AppendLine("</ul>\n");
                    }
                }
            }
        }
        #endregion
        #region 获取远程文件的信息==============================
        private void get_remote_fileinfo(ActionExecutingContext context)
        {
            string filePath = Request.Form["remotepath"];
            if (string.IsNullOrEmpty(filePath))
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"没有找到远程附件地址！\"}");
                return;
            }
            if (!filePath.ToLower().StartsWith("http://")&& !filePath.ToLower().StartsWith("https://"))
            {
                context.Result = Content("{\"status\": 0, \"msg\": \"不是远程附件地址！\"}");
                return;
            }
            try
            {
                HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(filePath);
                HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
                int fileSize = (int)_response.ContentLength;
                string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
                string fileExt = filePath.Substring(filePath.LastIndexOf(".") + 1).ToUpper();
                context.Result = Content("{\"status\": 1, \"msg\": \"获取远程文件成功！\", \"name\": \"" + fileName + "\", \"path\": \"" + filePath + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}");
                return;
            }
            catch
            {
                context.Result = Content("{\"status\": 0, \"msg\": \"远程文件不存在！\"}");
                return;
            }
        }
        #endregion
        #region 发送手机短信====================================
        private void sms_message_post(ActionExecutingContext context)
        {
            string mobiles = Request.Form["mobiles"];
            string content = Request.Form["content"];
            if (mobiles == "")
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"手机号码不能为空！\"}");
                return;
            }
            if (content == "")
            {
                context.Result = Content("{\"status\": 0, \"msg\": \"短信内容不能为空！\"}");
                return;
            }
            //开始发送
            string msg = string.Empty;
            bool result = true;//TODO Send(mobiles, content, 2, out msg);
            if (result)
            {
                context.Result = Content("{\"status\": 1, \"msg\": \"" + msg + "\"}");
                return;
            }
            context.Result = Content("{\"status\": 0, \"msg\": \"" + msg + "\"}");
            return;
        }
        #endregion
        #region 修改订单信息和状态==============================
        private void edit_order_status(ActionExecutingContext context)
        {
            //取得管理员登录信息
            Manager adminInfo = GetAdminInfo();
            if (adminInfo == null)
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"未登录或已超时，请重新登录！\"}");
                return;
            }
            string order_no = CMSRequest.GetString("order_no",context.HttpContext);
            string edit_type = CMSRequest.GetString("edit_type", context.HttpContext);
            if (order_no == "")
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"传输参数有误，无法获取订单号！\"}");
                return;
            }
            if (edit_type == "")
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"无法获取修改订单类型！\"}");
                return;
            }

            Orders model = _orders.GetModel(order_no);
            if (model == null)
            {
                context.Result=Content("{\"status\": 0, \"msg\": \"订单号不存在或已被删除！\"}");
                return;
            }
            switch (edit_type.ToLower())
            {
                case "order_confirm": //确认订单
                                      //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有确认订单的权限！\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经确认，不能重复处理！\"}");
                        return;
                    }
                    model.status = 2;
                    model.confirm_time = DateTime.Now;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单确认失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Confirm.ToString(), "确认订单号:" + model.order_no,CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    #region 发送短信或邮件============================
                    if (orderConfig.confirmmsg > 0)
                    {
                        switch (orderConfig.confirmmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >对方未填写手机号码！\"}");
                                    return;
                                }
                                Sms_template smsModel = _sms_template.GetModel(orderConfig.confirmcallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >短信通知模板不存在！\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", sysConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.accept_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = sendSMS.Send(model.mobile,smsModel.code,msgContent);
                                if (!sendStatus)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                    //取得用户的邮箱地址
                                if (string.IsNullOrEmpty(model.email))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >该用户没有填写邮箱地址。\"}");
                                    return;
                                }
                                //取得邮件模板内容
                                Mail_template mailModel = _mail_template.GetModel(orderConfig.confirmid);
                                if (mailModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                    return;
                                }
                                //替换标签
                                string mailTitle = mailModel.maill_title;
                                mailTitle = mailTitle.Replace("{username}", model.user_name);
                                string mailContent = mailModel.content;
                                mailContent = mailContent.Replace("{webname}", sysConfig.webname);
                                mailContent = mailContent.Replace("{weburl}", sysConfig.weburl);
                                mailContent = mailContent.Replace("{webtel}", sysConfig.webtel);
                                mailContent = mailContent.Replace("{username}", model.user_name);
                                mailContent = mailContent.Replace("{orderno}", model.order_no);
                                mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                //发送邮件
                                CMSMail.sendMail(sysConfig.emailsmtp, sysConfig.emailssl, sysConfig.emailusername,
                                    AESEncryptHelper.Decode(sysConfig.emailpassword, sysConfig.sysencryptstring),
                                    sysConfig.emailnickname, sysConfig.emailfrom, model.email, mailTitle, mailContent);
                                break;
                        }
                    }
                    #endregion
                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功！\"}");
                    break;
                case "order_payment": //确认付款
                                      //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有确认付款的权限！\"}");
                        return;
                    }
                    if (model.status > 1 || model.payment_status == 2)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已确认，不能重复处理！\"}");
                        return;
                    }
                    model.payment_status = 2;
                    model.payment_time = DateTime.Now;
                    model.status = 2;
                    model.confirm_time = DateTime.Now;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单确认付款失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Confirm.ToString(), "确认付款订单号:" + model.order_no,CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    #region 发送短信或邮件
                    if (orderConfig.confirmmsg > 0)
                    {
                        switch (orderConfig.confirmmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >对方未填写手机号码！\"}");
                                    return;
                                }
                                Sms_template smsModel = _sms_template.GetModel(orderConfig.confirmcallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >短信通知模板不存在！\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", sysConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = sendSMS.Send(model.mobile, smsModel.code, msgContent);
                                if (!sendStatus)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                    //取得用户的邮箱地址
                                if (string.IsNullOrEmpty(model.email))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >该用户没有填写邮箱地址。\"}");
                                    return;
                                }
                                //取得邮件模板内容
                                Mail_template mailModel = _mail_template.GetModel(orderConfig.confirmid);
                                if (mailModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                    return;
                                }
                                //替换标签
                                string mailTitle = mailModel.maill_title;
                                mailTitle = mailTitle.Replace("{username}", model.user_name);
                                string mailContent = mailModel.content;
                                mailContent = mailContent.Replace("{webname}", sysConfig.webname);
                                mailContent = mailContent.Replace("{weburl}", sysConfig.weburl);
                                mailContent = mailContent.Replace("{webtel}", sysConfig.webtel);
                                mailContent = mailContent.Replace("{username}", model.user_name);
                                mailContent = mailContent.Replace("{orderno}", model.order_no);
                                mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                //发送邮件
                                CMSMail.sendMail(sysConfig.emailsmtp, sysConfig.emailssl, sysConfig.emailusername,
                                    AESEncryptHelper.Decode(sysConfig.emailpassword, sysConfig.sysencryptstring),
                                    sysConfig.emailnickname, sysConfig.emailfrom, model.email, mailTitle, mailContent);
                                break;
                        }
                    }
                    #endregion
                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认付款成功！\"}");
                    break;
                case "order_express": //确认发货
                                      //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有确认发货的权限！\"}");
                        return;
                    }
                    if (model.status > 2 || model.express_status == 2)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已完成或已发货，不能重复处理！\"}");
                        return;
                    }
                    int express_id = int.Parse(Request.Form["express_id"]);
                    string express_no = Request.Form["express_no"];
                    if (express_id == 0)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"请选择配送方式！\"}");
                        return;
                    }
                    model.express_id = express_id;
                    model.express_no = express_no;
                    model.express_status = 2;
                    model.express_time = DateTime.Now;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单发货失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Confirm.ToString(), "确认发货订单号:" + model.order_no,CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    #region 发送短信或邮件============================
                    if (orderConfig.expressmsg > 0)
                    {
                        switch (orderConfig.expressmsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >对方未填写手机号码！\"}");
                                    return;
                                }
                                Sms_template smsModel = _sms_template.GetModel(orderConfig.expresscallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >短信通知模板不存在！\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", sysConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = sendSMS.Send(model.mobile, smsModel.code, msgContent);
                                if (!sendStatus)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                    //取得用户的邮箱地址
                                if (string.IsNullOrEmpty(model.email))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >该用户没有填写邮箱地址。\"}");
                                    return;
                                }
                                //取得邮件模板内容
                                Mail_template mailModel = _mail_template.GetModel(orderConfig.expressid);
                                if (mailModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                    return;
                                }
                                //替换标签
                                string mailTitle = mailModel.maill_title;
                                mailTitle = mailTitle.Replace("{username}", model.user_name);
                                string mailContent = mailModel.content;
                                mailContent = mailContent.Replace("{webname}", sysConfig.webname);
                                mailContent = mailContent.Replace("{weburl}", sysConfig.weburl);
                                mailContent = mailContent.Replace("{webtel}", sysConfig.webtel);
                                mailContent = mailContent.Replace("{username}", model.user_name);
                                mailContent = mailContent.Replace("{orderno}", model.order_no);
                                mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                //发送邮件
                                CMSMail.sendMail(sysConfig.emailsmtp, sysConfig.emailssl, sysConfig.emailusername,
                                    AESEncryptHelper.Decode(sysConfig.emailpassword, sysConfig.sysencryptstring),
                                    sysConfig.emailnickname, sysConfig.emailfrom, model.email, mailTitle, mailContent);
                                break;
                        }
                    }
                    #endregion
                    context.Result=Content("{\"status\": 1, \"msg\": \"订单发货成功！\"}");
                    break;
                case "order_complete": //完成订单=========================================
                                       //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Confirm.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有确认完成订单的权限！\"}");
                        return;
                    }
                    if (model.status > 2)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经完成，不能重复处理！\"}");
                        return;
                    }
                    model.status = 3;
                    model.complete_time = DateTime.Now;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"确认订单完成失败！\"}");
                        return;
                    }
                    //给会员增加积分检查升级
                    if (model.user_id > 0 && model.point > 0)
                    {
                        _user_point_log.Add(model.user_id, model.user_name, model.point, "购物获得积分，订单号：" + model.order_no, true);
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Confirm.ToString(), "确认交易完成订单号:" + model.order_no,CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    #region 发送短信或邮件=========================
                    if (orderConfig.completemsg > 0)
                    {
                        switch (orderConfig.completemsg)
                        {
                            case 1: //短信通知
                                if (string.IsNullOrEmpty(model.mobile))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >对方未填写手机号码！\"}");
                                    return;
                                }
                                Sms_template smsModel = _sms_template.GetModel(orderConfig.completecallindex); //取得短信内容
                                if (smsModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >短信通知模板不存在！\"}");
                                    return;
                                }
                                //替换标签
                                string msgContent = smsModel.content;
                                msgContent = msgContent.Replace("{webname}", sysConfig.webname);
                                msgContent = msgContent.Replace("{username}", model.user_name);
                                msgContent = msgContent.Replace("{orderno}", model.order_no);
                                msgContent = msgContent.Replace("{amount}", model.order_amount.ToString());
                                //发送短信
                                string tipMsg = string.Empty;
                                bool sendStatus = sendSMS.Send(model.mobile, smsModel.code, msgContent);
                                if (!sendStatus)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送短信<br/ >" + tipMsg + "\"}");
                                    return;
                                }
                                break;
                            case 2: //邮件通知
                                    //取得用户的邮箱地址
                                if (string.IsNullOrEmpty(model.email))
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >该用户没有填写邮箱地址。\"}");
                                    return;
                                }
                                //取得邮件模板内容
                                Mail_template mailModel = _mail_template.GetModel(orderConfig.completeid);
                                if (mailModel == null)
                                {
                                    context.Result=Content("{\"status\": 1, \"msg\": \"订单确认成功，但无法发送邮件<br/ >邮件通知模板不存在。\"}");
                                    return;
                                }
                                //替换标签
                                string mailTitle = mailModel.maill_title;
                                mailTitle = mailTitle.Replace("{username}", model.user_name);
                                string mailContent = mailModel.content;
                                mailContent = mailContent.Replace("{webname}", sysConfig.webname);
                                mailContent = mailContent.Replace("{weburl}", sysConfig.weburl);
                                mailContent = mailContent.Replace("{webtel}", sysConfig.webtel);
                                mailContent = mailContent.Replace("{username}", model.user_name);
                                mailContent = mailContent.Replace("{orderno}", model.order_no);
                                mailContent = mailContent.Replace("{amount}", model.order_amount.ToString());
                                //发送邮件
                                CMSMail.sendMail(sysConfig.emailsmtp, sysConfig.emailssl, sysConfig.emailusername,
                                    AESEncryptHelper.Decode(sysConfig.emailpassword, sysConfig.sysencryptstring),
                                    sysConfig.emailnickname, sysConfig.emailfrom, model.email, mailTitle, mailContent);
                                break;
                        }
                    }
                    #endregion
                    context.Result=Content("{\"status\": 1, \"msg\": \"确认订单完成成功！\"}");
                    break;
                case "order_cancel": //取消订单==========================================
                                     //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Cancel.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有取消订单的权限！\"}");
                        return;
                    }
                    if (model.status > 2)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经完成，不能取消订单！\"}");
                        return;
                    }
                    model.status = 4;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"取消订单失败！\"}");
                        return;
                    }
                    int check_revert1 = int.Parse(Request.Form["check_revert"]);
                    if (check_revert1 == 1)
                    {
                        //如果存在积分换购则返还会员积分
                        if (model.user_id > 0 && model.point < 0)
                        {
                            _user_point_log.Add(model.user_id, model.user_name, (model.point * -1), "取消订单返还积分，订单号：" + model.order_no, false);
                        }
                        //如果已支付则退还金额到会员账户
                        if (model.user_id > 0 && model.payment_status == 2 && model.order_amount > 0)
                        {
                            _user_amount_log.Add(model.user_id, model.user_name, model.order_amount, "取消订单退还金额，订单号：" + model.order_no);
                        }
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Cancel.ToString(), "取消订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"取消订单成功！\"}");
                    break;
                case "order_invalid": //作废订单==========================================
                                      //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Invalid.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有作废订单的权限！\"}");
                        return;
                    }
                    if (model.status != 3)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单尚未完成，不能作废订单！\"}");
                        return;
                    }
                    model.status = 5;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"作废订单失败！\"}");
                        return;
                    }
                    int check_revert2 = int.Parse(Request.Form["check_revert"]);
                    if (check_revert2 == 1)
                    {
                        //扣除购物赠送的积分
                        if (model.user_id > 0 && model.point > 0)
                        {
                            _user_point_log.Add(model.user_id, model.user_name, (model.point * -1), "作废订单扣除积分，订单号：" + model.order_no, false);
                        }
                        //退还金额到会员账户
                        if (model.user_id > 0 && model.order_amount > 0)
                        {
                            _user_amount_log.Add(model.user_id, model.user_name, model.order_amount - model.express_fee, "取消订单退还金额，订单号：" + model.order_no);
                        }
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Invalid.ToString(), "作废订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"作废订单成功！\"}");
                    break;
                case "edit_accept_info": //修改收货信息====================================
                                         //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有修改收货信息的权限！\"}");
                        return;
                    }
                    if (model.express_status == 2)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经发货，不能修改收货信息！\"}");
                        return;
                    }
                    string accept_name = Request.Form["accept_name"];
                    string province = Request.Form["province"];
                    string city = Request.Form["city"];
                    string area = Request.Form["area"];
                    string address = Request.Form["address"];
                    string post_code = Request.Form["post_code"];
                    string mobile = Request.Form["mobile"];
                    string telphone = Request.Form["telphone"];
                    string email = Request.Form["email"];

                    if (accept_name == "")
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"请填写收货人姓名！\"}");
                        return;
                    }
                    if (area == "")
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"请选择所在地区！\"}");
                        return;
                    }
                    if (address == "")
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"请填写详细的送货地址！\"}");
                        return;
                    }
                    if (mobile == "" && telphone == "")
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"联系手机或电话至少填写一项！\"}");
                        return;
                    }

                    model.accept_name = accept_name;
                    model.area = province + "," + city + "," + area;
                    model.address = address;
                    model.post_code = post_code;
                    model.mobile = mobile;
                    model.telphone = telphone;
                    model.email = email;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改收货人信息失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改收货信息，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改收货人信息成功！\"}");
                    break;
                case "edit_order_remark": //修改订单备注=================================
                    string remark = Request.Form["remark"];
                    if (remark == "")
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"请填写订单备注内容！\"}");
                        return;
                    }
                    model.remark = remark;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改订单备注失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改订单备注，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改订单备注成功！\"}");
                    break;
                case "edit_real_amount": //修改商品总金额================================
                                         //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有修改商品金额的权限！\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经确认，不能修改金额！\"}");
                        return;
                    }
                    decimal real_amount = decimal.Parse(Request.Form["real_amount"]);
                    model.real_amount = real_amount;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改商品总金额失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改商品金额，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改商品总金额成功！\"}");
                    break;
                case "edit_express_fee": //修改配送费用==================================
                                         //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有配送费用的权限！\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经确认，不能修改金额！\"}");
                        return;
                    }
                    decimal express_fee = decimal.Parse(Request.Form["express_fee"]);
                    model.express_fee = express_fee;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改配送费用失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改配送费用，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改配送费用成功！\"}");
                    break;
                case "edit_payment_fee": //修改支付手续费=================================
                                         //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有修改支付手续费的权限！\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经确认，不能修改金额！\"}");
                        return;
                    }
                    decimal payment_fee = decimal.Parse(Request.Form["payment_fee"]);
                    model.payment_fee = payment_fee;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改支付手续费失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改支付手续费，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改支付手续费成功！\"}");
                    break;
                case "edit_invoice_taxes": //修改发票税金=================================
                                           //检查权限
                    if (!_manager_role.Exists(adminInfo.role_id, "order_list", CMSEnums.ActionEnum.Edit.ToString()))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"您没有修改发票税金的权限！\"}");
                        return;
                    }
                    if (model.status > 1)
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"订单已经确认，不能修改金额！\"}");
                        return;
                    }
                    decimal invoice_taxes = decimal.Parse(Request.Form["invoice_taxes"]);
                    model.invoice_taxes = invoice_taxes;
                    if (!_orders.Update(model))
                    {
                        context.Result=Content("{\"status\": 0, \"msg\": \"修改订单发票税金失败！\"}");
                        return;
                    }
                    _manager_log.Add(adminInfo.id, adminInfo.user_name, CMSEnums.ActionEnum.Edit.ToString(), "修改订单发票税金，订单号:" + model.order_no, CMSRequest.GetClientUserIp(context.HttpContext)); //记录日志
                    context.Result=Content("{\"status\": 1, \"msg\": \"修改发票税金成功！\"}");
                    break;
            }

        }
        #endregion
        #region 发送红包====================================
        private void send_red_pack(ActionExecutingContext context)
        {
            JObject jobject = JObject.Parse(CMSRequest.GetFormString("json",context.HttpContext));
            JToken record = jobject["list"];
            int user_id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out user_id))
                {
                    var weixin = _user_oauth.GetModelByUserId(user_id);
                    if (weixin == null)
                    {
                        context.Result = Content("{\"status\": 0, \"msg\": \"未绑定微信！\"}");
                        return;
                    }
                    //开始打包
                    var mch = _site_payment.GetList(1, 1, "where title='微信支付'", "id desc").FirstOrDefault();
                    var app = _user_oauth_app.GetFirst();
                    string openid = weixin.oauth_openid;//用户openid
                    string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
                    //商户订单号 组成：mch_id+yyyymmdd+10位一天内不能重复的数字。 
                    string orderNo = mch.key1 + DateTime.Now.ToString("yyyymmdd") + Utils.Number(10);
                    //支付密钥(在商户平台设置32为字符串) 
                    string Code = mch.key2;//32为随机字符串; 

                    string key = "key=" + "";
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("act_name", "新人见面礼");//活动名称 
                    data.Add("client_ip", "120.210.205.66");//Ip地址 
                    data.Add("mch_billno", orderNo);//商户订单号 组成：mch_id+yyyymmdd+10位一天内不能重复的数字。 
                    data.Add("mch_id", mch.key2);//商户号 
                    data.Add("nonce_str", Code);//随机字符串 
                    data.Add("re_openid", openid);//用户openid 
                    data.Add("remark", "分享越多抢的越多，快来抢！");//备注 
                    data.Add("send_name", sysConfig.webname);//商户名称 
                    data.Add("total_amount", "100");//付款金额 单位分 
                    data.Add("total_num", "1");//红包发放总人数 
                    data.Add("wishing", "恭喜发财");//红包祝福语 
                    data.Add("wxappid", app.oauth_app_id);//公众账号appid 
                    string xml = GetXML(data, key);//签名+拼接xml 
                    string str = PostWebRequests(url, xml, mch.key1);//微信返回xml err_code=SUCCESS 就是成功
                    if (str.Contains("SUCCESS"))
                    {
                        context.Result = Content("{\"status\": 1, \"msg\": \"发放成功\"}");
                        return;
                    }
                    context.Result = Content("{\"status\": 0, \"msg\": \"失败:" + str + "\"}");
                    return;
                }
            }
        }
        //发送红包(MD5签名+拼接XML)
        private static string GetXML(Dictionary<string, string> data, string paykey)
        {
            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            var data1 = from d in data orderby d.Key select d;
            string data2 = "";
            string XML = "<xml>";
            foreach (var item in data1)
            {
                //空值不参与签名
                if (item.Value + "" != "")
                {
                    data2 += item.Key + "=" + item.Value + "&";
                }
                XML += "<" + item.Key + ">" + item.Value + "" + "</" + item.Key + ">";
            }

            data2 += paykey;
            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBye = Encoding.UTF8.GetBytes(data2);
            }
            catch
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(data2);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            XML += "<sign>" + retStr + "</sign>";//签名
            XML += "</xml>";
            return XML;
        }
        //发送红包请求Post方法
        private string PostWebRequests(string postUrl, string menuInfo,string password)
        {
            string path = System.IO.Path.Combine(_env.ContentRootPath,"apiclient_cert.p12");

            //HttpClient请求，在handler里添加X509Certificate2 证书，数据data是byte[] 类型，所以需要使用ByteArrayContent传入
            var handler = new HttpClientHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.SslProtocols = SslProtocols.Tls12;
            //获取证书路径
            //商户私钥证书，用于对请求报文进行签名
            handler.ClientCertificates.Add(new X509Certificate2(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet));
            handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            //post请求
            var client = new HttpClient(handler);
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(menuInfo);
                ms.Write(bytes, 0, bytes.Length);
                ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置，否则发送无效
                HttpContent hc = new StreamContent(ms);
                var response = client.PostAsync(postUrl, hc).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion
        #region 发送现金====================================
        private void send_cash(ActionExecutingContext context)
        {
            JObject jobject = JObject.Parse(CMSRequest.GetFormString("json", context.HttpContext));
            JToken record = jobject["list"];
            int user_id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out user_id))
                {
                    var weixin = _user_oauth.GetModelByUserId(user_id);
                    if (weixin == null)
                    {
                        context.Result = Content("{\"status\": 0, \"msg\": \"未绑定微信！\"}");
                        return;
                    }
                    //开始打包
                    var mch = _site_payment.GetList(1, 1, "where title='微信支付'", "id desc").FirstOrDefault();
                    var app = _user_oauth_app.GetFirst();
                    string openid = weixin.oauth_openid;//用户openid
                    string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
                    //商户订单号 组成：mch_id+yyyymmdd+10位一天内不能重复的数字。 
                    string orderNo = mch.key1 + DateTime.Now.ToString("yyyymmdd") + Utils.Number(10);
                    //支付密钥(在商户平台设置32为字符串) 
                    string Code = mch.key2;//32为随机字符串; 

                    string key = "key=" + "";
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("mch_appid", app.oauth_app_id);//活动名称 
                    data.Add("mch_id", mch.key2);//商户号 
                    data.Add("nonce_str", Code);//随机字符串 
                    data.Add("sign", "");//签名 
                    data.Add("partner_trade_no", orderNo);//商户订单号 组成：mch_id+yyyymmdd+10位一天内不能重复的数字。
                    data.Add("openid", openid);//用户openid 
                    data.Add("check_name", "FORCE_CHECK");//强校验真实姓名 
                    data.Add("amount", "100");//付款金额 单位分 
                    data.Add("desc", "工资");//备注 
                    data.Add("spbill_create_ip", "120.210.205.66");//Ip地址                    
                    string xml = GetXML(data, key);//签名+拼接xml 
                    string str = PostWebRequests(url, xml, mch.key1);//微信返回xml err_code=SUCCESS 就是成功
                    if (str.Contains("SUCCESS"))
                    {
                        context.Result = Content("{\"status\": 1, \"msg\": \"发放成功\"}");
                        return;
                    }
                    context.Result = Content("{\"status\": 0, \"msg\": \"失败:" + str + "\"}");
                    return;
                }
            }
        }
        #endregion
    }
}